package com.jxc.jxcmanage.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jxc.jxcmanage.code.entity.ProductInventory;
import com.jxc.jxcmanage.code.mapper.ProductInventoryMapper;
import com.jxc.jxcmanage.common.ResultBean;
import com.jxc.jxcmanage.constants.Constant;
import com.jxc.jxcmanage.dto.ProductInventoryDto;
import com.jxc.jxcmanage.util.DateUtils;
import com.jxc.jxcmanage.util.ExcelUtil;
import com.jxc.jxcmanage.util.HttpUtil;
import com.jxc.jxcmanage.util.StringUtil;

@Service
public class ProductInventoryService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProductInventoryService.class);

	@Autowired
	private ProductInventoryMapper productInventoryMapper;

	/**
	 * 保存
	 * 
	 * @param param
	 * @return
	 */
	@Transactional
	public ResultBean save(final ProductInventoryDto param) {
		ResultBean bean = null;
		ProductInventory product = new ProductInventory();
		BeanUtils.copyProperties(param, product);
		try {
			product.setCreatedDate(new Date());
			product.setUpdatedDate(new Date());
			productInventoryMapper.insertSelective(product);
		} catch (Exception e) {
			e.printStackTrace();
			return bean = ResultBean.fail(String.format(Constant.LOG_FORMAT, "库存数据"));
		}
		bean = ResultBean.success();
		return bean;
	}


	/**
	 * 更新或者保存
	 * 
	 * @param param
	 * @return
	 */
	public ResultBean addOrUpdateInfo(final ProductInventoryDto param) {
		// 更新
		param.setUpdatedBy(Constant.DEFAULT_BY);
		if (param.getId() != null && param.getId().intValue() > 0) {
			return update(param);
		} else {// 新增
			param.setStatus(1);// 默认1
			param.setCreatedBy(Constant.DEFAULT_BY);
			return save(param);
		}
	}

	/**
	 * 更新数据，加锁防止并发数据不一致
	 * 
	 * @param param
	 * @return
	 */
	@Transactional
	public synchronized ResultBean update(final ProductInventoryDto param) {
		ResultBean bean = null;
		try {
			ProductInventory old = productInventoryMapper.selectByPrimaryKey(param.getId());
			if (!ObjectUtils.isEmpty(param.getNote())) {
				old.setNote(param.getNote());
			}
			if (param.getSupplierId() > 0) {
				old.setSupplierId(param.getSupplierId());
			}
			if (param.getProductId() > 0) {
				old.setProductId(param.getProductId());
			}
			if (param.getSold() > 0) {
				old.setSold(param.getSold());
			}
			if (param.getSurplus() > 0) {
				old.setSurplus(param.getSurplus());
			}
			if (param.getTotal() > 0) {
				old.setTotal(param.getTotal());
			}
			if (!ObjectUtils.isEmpty(param.getNote())) {
				old.setNote(param.getNote());
			}
			old.setUpdatedDate(new Date());
			productInventoryMapper.updateByPrimaryKeySelective(old);
			ProductInventory now = productInventoryMapper.selectByPrimaryKey(param.getId());
			String result = StringUtil.compareModel(old, now);
			LOGGER.info("......{}......", result);
		} catch (Exception e) {
			e.printStackTrace();
			return bean = ResultBean.fail(String.format(Constant.LOG_FORMAT, "产品数据"));
		}
		bean = ResultBean.success();
		return bean;
	}

	/**
	 * 保存
	 * 
	 * @param param
	 * @return
	 */
	@Transactional
	public ResultBean delete(final ProductInventoryDto param) {
		try {
			productInventoryMapper.deleteByPrimaryKey(param.getId());
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.fail(String.format(Constant.LOG_FORMAT, "产品数据"));
		}
		return ResultBean.success();
	}

	/**
	 * 分页查询
	 * 
	 * @param param
	 * @return
	 */
	public ResultBean page(final ProductInventoryDto param) {
		PageInfo<ProductInventoryDto> page = null;
		Map<String, Object> resultData = new HashMap<>();
		try {
			PageHelper.startPage(param.getPageNumber(), param.getPageSize());
			page = new PageInfo<>(productInventoryMapper.list(param));
			resultData.put("total", page.getTotal());
			resultData.put("rows", page.getList());
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.fail();
		}
		return ResultBean.success(resultData);
	}

	/**
	 * 数据导入
	 * 
	 * @param param
	 * @return
	 */
	public ResultBean list(final ProductInventoryDto param) {
		List<ProductInventoryDto> list = null;
		try {
			list = productInventoryMapper.list(param);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.fail();
		}
		return ResultBean.success(list);
	}


	public ResultBean exportCsv(ProductInventoryDto param) {
		List<ProductInventoryDto> list = productInventoryMapper.list(param);
		String title[] = new String[] { "序号", "产品名称", "产品编码", "供应商名称", "单位", "规格", "已售出", "库存", "总共", "备注" };
		ProductInventoryDto dto = null;
		String totalValue[][] = new String[10][title.length + Constant.ONE];
		for (int i = 0; i < list.size(); i++) {
			dto = list.get(i);
			String rowValue[] = new String[] { i + Constant.EMPTY, dto.getProductName(), dto.getProductCode(),
					dto.getSupplierName(), dto.getUnit(), dto.getSpecs(), dto.getSold() + Constant.EMPTY,
					dto.getSurplus() + Constant.EMPTY, dto.getTotal() + Constant.EMPTY, dto.getNote() };
			totalValue[i] = rowValue;
		}
		try {
			HttpServletResponse response = HttpUtil.getHttpServletResponse();
			response.setContentType("charset=UTF-8"); // 设置编码字符
			String filename = Constant.STORAGE + DateUtils.parse(new Date(), DateUtils.YYYYMMDDHHMMSSsss) + Constant.XLS_SUFFIX;
			HttpUtil.setReponseHeader(filename, response);
			HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(Constant.STORAGE + Constant.XLS_SUFFIX, title, totalValue);
			File file = ExcelUtil.createExcel(wb, FileUtils.getTempDirectoryPath());
			if (!file.exists()) {
				file.mkdirs();
			}
			OutputStream os = new FileOutputStream(FileUtils.getTempDirectoryPath() + filename);
			InputStream in = new FileInputStream(FileUtils.getTempDirectoryPath() + filename);
			int b;
			while ((b = in.read()) != -1) { // 如果没有到达流的尾部
				os.write(b); //
			}
			os.flush();
			in.close(); // 关闭流
			os.close(); // 将流关闭
		} catch (Exception e) {
			LOGGER.error("生成计费明细CSV异常", e);
			return ResultBean.fail();
		}
		return ResultBean.success();
	}

	public ProductInventoryDto findBySupplierAndProduct(final ProductInventoryDto param) {
		ProductInventoryDto dto = productInventoryMapper.findBySupplierAndProduct(param);
		return dto;
	}
}
